﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QueueUnlimited.API;
using System.Diagnostics;
using System.Transactions;
using MultiplayerDice.Implementation.BusinessEvent;

namespace MultiplayerDice.Implementation.Processor
{
    public static class OpenGamesProcessor
    {
        public static void Process(GenericEvent genericEvent)
        {
            try
            {
                var startedGame = genericEvent.IsOfTypeOrNull<NewGameStartedEvent>();
                var endedGame = genericEvent.IsOfTypeOrNull<ExistingGameEndedEvent>();

                if (startedGame != null)
                {
                    using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
                    using (var database = new QueryDataStoreContext())
                    {
                        database.Query_OpenGames.InsertOnSubmit(new Query_OpenGame()
                        {
                            GameId = startedGame.GameId,
                            InsertDateTime = startedGame.DateTimeOfStart,
                            Player1 = startedGame.Player,
                            Player2 = startedGame.OpponentPlayer,
                            Player1Diced = startedGame.Diced
                        });
                        database.SubmitChanges();
                    }
                }
                else if (endedGame != null)
                {
                    using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
                    using (var database = new QueryDataStoreContext())
                    {
                        database.Query_OpenGames.DeleteOnSubmit(
                            (from x in database.Query_OpenGames
                             where x.GameId == endedGame.GameId
                             select x).First());
                        database.SubmitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                throw;
            }
        }
    }
}